/*
 * @Description: 包含一个loading和promise。在promise启动和停止前改变loading
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2023-10-14
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2023-10-27
 */

import { readonly, ref } from 'vue'

/**
 * 包含一个loading和promise。在promise启动和停止前改变loading
 * @param fn promise
 * @returns
 */
export const useLoading = <F extends (...args: any) => Promise<any>>(fn: F) => {
  const loading = ref(false)
  const firstLoaded = ref(false)

  const trigger = (async (...args: any) => {
    loading.value = true
    const res = await fn?.(...args).finally(() => (loading.value = false))
    firstLoaded.value = true
    return res
  }) as F

  return {
    loading: readonly(loading),
    firstLoaded: readonly(firstLoaded),
    trigger,
  }
}
